package com.zhou.springboot.web;


import com.zhou.springboot.dto.PersonResponseInfo;
import com.zhou.springboot.entity.Person;
import com.zhou.springboot.service.PersonService;
import io.swagger.annotations.*;
import javafx.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 @ApiImplicitParams：用在请求的方法上，表示一组参数说明
 @ApiImplicitParam：用在@ApiImplicitParams注解中，指定一个请求参数的各个方面
     name：参数名
     value：参数的汉字说明、解释
     required：参数是否必须传
     paramType：参数放在哪个地方
     · header --> 请求参数的获取：@RequestHeader
     · query --> 请求参数的获取：@RequestParam
     · path（用于restful接口）--> 请求参数的获取：@PathVariable
     · body（不常用）
     · form（不常用）
     dataType：参数类型，默认String，其它值dataType="Integer"
     defaultValue：参数的默认值
 */

@RestController
@RequestMapping(value = "api/person")
@Api(value = "用户接口", tags = {"用户相关接口"})//swagger控制器说明注解
public class PersonController {
    private static final Logger logger = LoggerFactory.getLogger(PersonController.class.getName());
    @Autowired
    private PersonService personService;
    // 此注解定义接口的一些说明信息
    @ApiOperation(value = "保存用户", notes = "传入用户信息JSON")
    // 定义参数信息
    @ApiImplicitParams({
            @ApiImplicitParam(name = "person", value = "用户信息", required = true, dataType = "Person")
    })
    // @RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)
    @RequestMapping(value = "", method = RequestMethod.POST)
    public PersonResponseInfo insertPerson(
            // @ApiParam主要用来标注参数信息
            @RequestBody Person person){
        System.out.println(person + "-------====-------");
        PersonResponseInfo apiResp = new PersonResponseInfo();
        logger.info("=====person:"+ person + "=====");
        try{
            personService.insertPerson(person);
            apiResp.setHttpStatus(HttpStatus.OK);
            apiResp.setStrMsg("success");
        }catch (Exception e){
            logger.error("出错了。。。。。。。。。。。。。。");
            logger.error("Unexpected error in " , e);
            apiResp.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            apiResp.setStrMsg("fail");
        }
        return apiResp;
    }
    @ApiOperation(value = "删除用户", notes = "请传入用户ID")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, dataType = "Long", value = "用户ID")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE,produces = "application/json")
    // 通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
    // 不使用占位符会导致Swagger请求报404
    public PersonResponseInfo deletePerson(@PathVariable Long id){
        PersonResponseInfo apiResp = new PersonResponseInfo();
        logger.info(String.valueOf((id instanceof Long)));
        logger.info("======" + id);
        try {
            personService.deletePerson(id);
            apiResp.setHttpStatus(HttpStatus.OK);
            apiResp.setStrMsg("success");
        } catch (Exception e) {
            logger.error("出错了。。。。。。。。。。。。。。");
            logger.error("Unexpected error in " , e);
            apiResp.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            apiResp.setStrMsg("fail");
        }
        return apiResp;
    }
    @ApiOperation(value = "更新用户", notes = "传入用户详细信息，会根据ID更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "person", value = "用户信息", required = true, dataType = "Person")
    })
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public PersonResponseInfo updatePerson(
            // @ApiParam主要用来标注参数信息
            @RequestBody Person person){
        PersonResponseInfo apiResp = new PersonResponseInfo();
        try{
            System.out.println(person + "================");
            personService.updatePerson(person);
            apiResp.setHttpStatus(HttpStatus.OK);
            apiResp.setStrMsg("success");
        }catch (Exception e){
            logger.error("出错了。。。。。。。。。。。。。。");
            logger.error("Unexpected error in " , e);
            apiResp.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            apiResp.setStrMsg("fail");
        }
        return apiResp;
    }
    @ApiOperation(value = "查找全部", notes = "查找全部")
    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json")
    public PersonResponseInfo findAllPerson(){
        List<Person> personList = null;
        PersonResponseInfo apiResp = new PersonResponseInfo();
        try {
            personList = personService.findAllPerson();
            apiResp.setHttpStatus(HttpStatus.OK);
            apiResp.setStrMsg("success");
            apiResp.setPersonData(personList);
        } catch (Exception e) {
            logger.error("出错了。。。。。。。。。。。。。。");
            logger.error("Unexpected error in " , e);
            apiResp.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            apiResp.setStrMsg("fail");
            apiResp.setPersonData(null);
        }
        return apiResp;
    }
    @ApiOperation(value = "通过Id查找用户信息", notes = "传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Long")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
    public PersonResponseInfo getPersonById(@PathVariable Long id){
        List<Person> personList = new ArrayList<Person>();
        PersonResponseInfo apiResp = new PersonResponseInfo();
        try {

            Person person=  personService.findPersonById(id);
            personList.add(person);
            apiResp.setHttpStatus(HttpStatus.OK);
            apiResp.setStrMsg("success");
            apiResp.setPersonData(personList);
        } catch (Exception e) {
            logger.error("出错了。。。。。。。。。。。。。。");
            logger.error("Unexpected error in " , e);
            System.out.println(e.getClass());
            System.out.println(e instanceof NoSuchElementException);
            if(e instanceof NoSuchElementException){
                apiResp.setHttpStatus(HttpStatus.OK);
                apiResp.setStrMsg("no this person");
                apiResp.setPersonData(null);
                return apiResp;
            }
            apiResp.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            apiResp.setStrMsg("fail");
            apiResp.setPersonData(null);
        }
        return apiResp;
    }
}